/**
 * jims
 */
package com.jims.master.modules.drug.service;

import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.drug.dao.DrugImportDetailDao;
import com.jims.master.modules.drug.dao.DrugInfoDao;
import com.jims.master.modules.drug.entity.*;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.apache.poi.util.Internal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 入库记录详情Service
 * @author zhuq
 * @version 2017-03-16
 */
@Service
@Transactional(readOnly = true)
public class DrugImportDetailService extends CrudService<DrugImportDetailDao, DrugImportDetail> {
    @Autowired
    private DrugImportDetailDao drugImportDetailDao;
    @Autowired
    private DrugInfoService drugInfoService;
    @Autowired
    private DrugSupplierCataService drugSupplierCataService;
    @Autowired
    private DrugStorageDeptService drugStorageDeptService;
    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private DrugInfoDao drugInfoDao;

	public DrugImportDetail get(String id) {
		return super.get(id);
	}
	
	public List<DrugImportDetail> findList(DrugImportDetail drugImportDetail) {
		return super.findList(drugImportDetail);
	}
	
	public Page<DrugImportDetail> findPage(Page<DrugImportDetail> page, DrugImportDetail drugImportDetail) {
		return super.findPage(page, drugImportDetail);
	}
	
	@Transactional(readOnly = false)
	public int save(DrugImportDetail drugImportDetail) {
		return super.save(drugImportDetail);
	}
	
	@Transactional(readOnly = false)
	public int delete(DrugImportDetail drugImportDetail) {
		return super.delete(drugImportDetail);
	}

    //根据传来的drugStock数据组装成drugImportDetail数据
    public DrugImportDetail createData(DrugStock drugStock,int itemNo,String importMasterId){
        DrugImportDetail drugImportDetail=new DrugImportDetail();
        drugImportDetail.setMasterId(importMasterId);		// 主表Id
        drugImportDetail.setItemNo(String.valueOf(itemNo+1));	// 序号
        drugImportDetail.setDrugCode(drugStock.getDrugCode());		// 药品编码
        drugImportDetail.setInfoId(drugStock.getInfoId());		// drugInfoId
        drugImportDetail.setPackageNum(drugStock.getPackageNum());		// 包装数量
        drugImportDetail.setPackageSpec(drugStock.getPackageSpec());		// 包装规格
        drugImportDetail.setPackageUnits(drugStock.getPackageUnits());		// 包装单位
        drugImportDetail.setMinSpec(drugStock.getMinSpec());		// 最小规格
        drugImportDetail.setMinUnits(drugStock.getMinUnits());		// 最小单位
        drugImportDetail.setPurchasePrice(drugStock.getPurchasePrice() + "");		// 进货价
        drugImportDetail.setDiscount(drugStock.getDiscount());		// 折扣
        drugImportDetail.setBatchNo(drugStock.getBatchNo());		// 批号
        drugImportDetail.setExpireDate(drugStock.getExpireDate());		// 有效期
        Double number=0.0;
        DrugInfo drugInfo=drugInfoDao.get(drugStock.getInfoId());
        if(drugStock.getPackageSpec().equals(drugInfo.getPackageSpec())){
            number= drugStock.getQuantity() * Integer.parseInt(drugStock.getPackageNum());
        }else {
            number= drugStock.getQuantity();
        }
        drugImportDetail.setQuantity(String.valueOf(number));		// 小包装库存量
        drugImportDetail.updateOrgId();		// 机构ID
        drugImportDetail.preInsert();
        return drugImportDetail;
    }
    /**
     * 出库单据查询
     * @param page 分页对象
     * @param drugImportDetail
     * @return
     */
    public Page<DrugImportDetail> findDetailsList(Page<DrugImportDetail> page, DrugImportDetail drugImportDetail) {
        drugImportDetail.updateOrgId();
        drugImportDetail.setPage(page);
        page.setList(drugImportDetailDao.findDetailsList(drugImportDetail));
        return page;
    }
    /**
     * 入库详情查询
     * @param drugImportDetail
     * @return
     */
    public List<DrugImportDetail> findBymasterId(DrugImportDetail drugImportDetail) {
        drugImportDetail.updateOrgId();
        return dao.findBymasterId(drugImportDetail);
    }

    /**
     * 药品入库单据打印
     * @param drugImportDetail
     * @return
     */
    public String drugImportDetailsPrint(DrugImportDetail drugImportDetail){
        User user = UserUtils.getUser();
        String deptId=null!=user.getOrgDept()?user.getOrgDept().getId():"";
        drugImportDetail.setStorageId(deptId);
        List<BaseDto> list= dao.findDetailsListPrint(drugImportDetail);
        DrugImportDetail entityForNum=dao.findNumByName(drugImportDetail);
        int num=entityForNum.getNum();
        Map map = new HashMap();
        String hospital = UserUtils.getUser().getCompany().getOrgName();
        String title="药品入库凭证";
        Double tradePriceTotal=0.0;
        Double retailPriceTotal=0.0;
        if(list.size()>0){
            BaseDto detail=list.get(0);
            map.put("storageName",detail.getAsString("storageName"));//收货库房
//            map.put("importClass",DictUtils.getDictLabel(detail.getAsString("importClass"), "DRUG_STOTARG_TYPE", ""));//入库类别
            map.put("importClass",detail.getAsString("importClass"));
            map.put("documentNo",detail.getAsString("documentNo"));//入库单号
            map.put("importDate",detail.getAsString("importDate"));//入库日期
            if(StringUtils.isBlank(detail.getAsString("supplierJc"))){
                DrugStorageDept drugStorageDept=drugStorageDeptService.get(detail.getAsString("storageForm"));
                if(null!=drugStorageDept){
                    map.put("receiver",drugStorageDept.getStorageName());//发货库房
                }
                else {
                    map.put("receiver","");
                }
            }
            else {
                DrugSupplierCata drugSupplierCata=drugSupplierCataService.get(detail.getAsString("supplierJc"));
                if(drugSupplierCata!=null){
                    map.put("receiver",drugSupplierCata.getSupplierJc());//发货厂商
                }
                else{
                    map.put("receiver","");//发货厂商
                }
            }
//            if("1".equals(drugImportDetail.getRemarks())){
//                map.put("receiver","");//发货厂商
//                map.put("storageName","");//收货库房
//            }
            int i=1;
            for(BaseDto detail1:list){
                DrugInfo drugInfo=drugInfoService.get(detail1.getAsString("infoId"));
                if(drugInfo!=null&&drugInfo.getPackageSpec().equals(detail1.getAsString("packageSpec"))){
                    detail1.put("quantity",Integer.parseInt(detail1.getAsString("quantity"))/Integer.parseInt(detail1.getAsString("packageNum")));
                }
                Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
                Matcher isNum = pattern.matcher(detail1.getAsString("minUnits"));
                if (isNum.matches()){
                    detail1.put("minUnits",DictUtils.getDictLabel(detail1.getAsString("minUnits"), "SPEC_UNIT", ""));
                }
                detail1.put("index",Integer.toString(i++));
                detail1.put("expireDate",detail1.getAsString("expireDate"));
                Double totalTrade=Double.parseDouble(detail1.getAsString("tradePrice"))*Double.parseDouble(detail1.getAsString("quantity"));
                Double totalRetail=Double.parseDouble(detail1.getAsString("retailPrice"))*Double.parseDouble(detail1.getAsString("quantity"));
                detail1.put("totalTrade",String.format("%.2f", totalTrade));
                detail1.put("totalRetail",String.format("%.2f",totalRetail));
                tradePriceTotal+=totalTrade;
                retailPriceTotal+=totalRetail;
            }
        }
        map.put("hospital",hospital);
        map.put("lists", list);
        map.put("title",title);
        map.put("num",num);//品种数量
        map.put("tradePriceTotal",String.format("%.2f", tradePriceTotal));
        map.put("retailPriceTotal",String.format("%.2f", retailPriceTotal));
        String printPath = PrintPdfUtils.previewPdf(user.getId(), "his/drug/drugImportDetailsPrint.jasper", map, list, "drugImportDetailsPrint");
        return  printPath;
    }
}